package MqttUtils

import (
	"crypto/tls"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"time"
)

type MqttPro struct {
	host     string
	clientId string
	username string
	password string
}

func MqttProOf(host, username, password, clientId string) *MqttPro {

	return &MqttPro{
		host:     host,
		username: username,
		password: password,
		clientId: clientId,
	}
}

func (this *MqttPro) Client(f mqtt.OnConnectHandler) (mqtt.Client, error) {

	connOpts := mqtt.NewClientOptions()

	connOpts.AddBroker(this.host)

	connOpts.ClientID = this.clientId
	connOpts.Username = this.username
	connOpts.Password = this.password

	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ClientAuth:         tls.NoClientCert,
	}

	connOpts.SetTLSConfig(tlsConfig)
	connOpts.SetConnectRetry(true)
	connOpts.SetConnectRetryInterval(5 * time.Second)
	connOpts.SetAutoReconnect(true)
	connOpts.SetMaxReconnectInterval(5 * time.Second)
	connOpts.SetPingTimeout(5 * time.Second)

	if f != nil {
		connOpts.OnConnect = f
	}

	c := mqtt.NewClient(connOpts)

	if token := c.Connect(); token.Wait() && token.Error() != nil {
		return nil, token.Error()
	}

	return c, nil
}
